//
//  EmotionInputController.swift
//  EmotionInput
//
//  Created by 杨兵 on 15/5/23.
//  Copyright (c) 2015年 bing. All rights reserved.
//  表情键盘

import UIKit


private let identifier = "emotionitem"

class EmoticonInputController: UIViewController {
    
    // 根据栏 
    lazy var toolbar: UIToolbar = {
        // 设置toolbars
        let toolbar = UIToolbar(frame: CGRectZero)
        toolbar.items = [UIBarButtonItem]()
        
        var count = 0
        for str in ["最近", "默认", "emoji", "浪小花"] {
            let btn = UIBarButtonItem(title: str, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:")
            toolbar.items?.append(btn)
            btn.tag = count
            if count++ < 3 {
                // 设置自动间距
                let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
                toolbar.items?.append(space)
            }
        }
        return toolbar
    }()
    
    
    // 表情集合视图
    lazy var collectionView: UICollectionView = {
        let width = UIScreen.mainScreen().bounds.width / 7
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSizeMake(width, width)
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        cv.delegate = self
        cv.dataSource = self
        cv.pagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        cv.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: identifier)
        
        return cv
    }()
    
    
    /**
        设置UI
    */
    func setupUI() {
        view.addSubview(toolbar)
        view.addSubview(collectionView)
        collectionView.backgroundColor = UIColor.whiteColor()
        
        // 使用制动布局的时候关掉autoresizing
        toolbar.setTranslatesAutoresizingMaskIntoConstraints(false)
        collectionView.setTranslatesAutoresizingMaskIntoConstraints(false)
        
        var cons = [AnyObject]()
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["toolbar": toolbar])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["collectionView": collectionView])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolbar(44)]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["collectionView": collectionView, "toolbar": toolbar])
        
        view.addConstraints(cons)
    }
    
    override func loadView() {
        super.loadView()
        
        // 设置界面
        setupUI()
    }
    
    
    // 选中的表情回调
    var selectedEmotioncs:((modal: EmoticonModal) -> ())?
    
    init(selectedModal:(modal: EmoticonModal) -> ()) {
        super.init(nibName: nil, bundle: nil)
        
        self.selectedEmotioncs = selectedModal
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // 表情数组
    lazy var emoticonList:[EmoticonModal] = {
        return EmoticonModal.emoticonsArray
    }()
    
    
    
    
    // 选中工具栏
    func clickItem(item: UIBarButtonItem) {
        var indexPath: NSIndexPath
        let pageCount = 21
        
        switch item.tag {
        case 1:
            indexPath = NSIndexPath(forItem: 1 * pageCount, inSection: 0)
        case 2:
            indexPath = NSIndexPath(forItem: 7 * pageCount, inSection: 0)
        case 3:
            indexPath = NSIndexPath(forItem: 11 * pageCount, inSection: 0)
        default:
            indexPath = NSIndexPath(forItem: 0, inSection: 0)
        }
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    
}


// MARK: - 代理
extension EmoticonInputController: UICollectionViewDataSource,UICollectionViewDelegate {
    
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emoticonList.count
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! EmoticonCell
        cell.emoticons = emoticonList[indexPath.item]
        return cell
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 将选中图插入视图中
        if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? EmoticonCell {
            self.selectedEmotioncs!(modal: cell.emoticons!)

        }
    }
    
}



// MARK: - EmoticonCell
class EmoticonCell:UICollectionViewCell {
    // 定义表情显示
    var emoteButton: UIButton?
    var emoticons: EmoticonModal? {
        didSet {
            if emoticons!.imagePath != nil {
                emoteButton?.setImage(UIImage(contentsOfFile: emoticons!.imagePath!), forState: UIControlState.Normal)
            }
            // 设置标题
            emoteButton?.setTitle(emoticons?.emojiStr, forState: UIControlState.Normal)
            // 设置大小
            emoteButton?.titleLabel?.font = UIFont.systemFontOfSize(32)
            // 删除按钮
            if emoticons!.isRemoveButton {
                emoteButton?.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoteButton?.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
            
            // 停用交互,如果不停用点击按钮会将事件传递到按钮层
            emoteButton?.userInteractionEnabled = false
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 在bounds中 偏移 4,4
        emoteButton = UIButton(frame: CGRectInset(bounds, 4, 4))
        addSubview(emoteButton!)
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}



